package com.twt.scclientandroid03;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.widget.ImageView;

public class SCClient03Activity extends Activity {
	/** Called when the activity is first created. */
	ImageView imgView = null;
	BitmapFactory.Options opts = new BitmapFactory.Options();
	Canvas canvas = new Canvas();
	BroadcastReceiver receiver = null;
	IntentFilter intentFilter = null;
	byte[] imgData = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		imgView = (ImageView) findViewById(R.id.imageView1);
		Intent intent = new Intent();
		intent.setClass(SCClient03Activity.this, BitmapServer.class);
		startService(intent);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(receiver);
		System.out.println("onPauser");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		receiver = new ImageMessageBroadcastReceiver();
		registerReceiver(receiver, getInterFilter());
		System.out.println("onResume");
	}

	protected IntentFilter getInterFilter() {
		if (intentFilter == null) {
			intentFilter = new IntentFilter();
			intentFilter.addAction("IMAGE_MESSAGE_ACTION");
		}
		return intentFilter;
	}

	class ImageMessageBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent intent) {
			// TODO Auto-generated method stub
			byte[] imageDatas = intent.getByteArrayExtra("IMAGE");
			Bitmap bitmap = getPicFromBytes(imageDatas, opts);
			drawImage(canvas, bitmap, 0, 0);
			imgView.setImageBitmap(bitmap);
		}

	}

	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	public static void drawImage(Canvas canvas, Bitmap bitmap, int x, int y) {
		canvas.drawBitmap(bitmap, x, y, null);
	}
}